from flask import Flask,request,jsonify
from conf import Config
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import json

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
CORS(app)


class User(db.Model):
    __tablename__='user'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(50),default='')
    age = db.Column(db.Integer,default=0)

class Shop(db.Model):
    __tablename__='shop'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    shop = db.Column(db.String(50),default='')
    price = db.Column(db.Float(7,2))
    join_time = db.Column(db.DateTime)
    content = db.Column(db.Text)
# db.drop_all()  #删除表

# db.create_all()  #创建表

@app.route('/user',methods=['POST','GET'])
def userm():
    if request.method == 'POST':
        data = json.loads(request.data)
        # data = request.form
        user = User(name=data['name'],age=data['age'])
        db.session.add(user)
        db.session.commit()
        return jsonify({'code':200})
    elif request.method == 'GET':
        
        res = User.query.all()
        print(res)
        list1 = []
        for i in res:
            dict1 = {}
            dict1['name'] = i.name
            dict1['age'] = i.age
            list1.append(dict1)
        print(list1)
        return 'ok'
@app.route('/shop',methods=['POST','GET'])
def shop():
    if request.method == 'POST':
        shop = request.form.get('shop')
        price = request.form.get('price')
        join_time = request.form.get('join_time')
        content = request.form.get('content')
        shops = Shop(shop=shop,price=price,join_time=join_time,content=content)
        db.session.add(shops)
        db.session.commit()
        return 'ok'
    



if __name__ == '__main__':
    app.run()
